﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Security.Cryptography;
using System.Web.Security;

using System.Globalization;

using Newtonsoft.Json.Linq;

using System.Net.Mail;
using System.Net.Mime;

namespace Training.Web.Support
{

    public class recRestructurDetailDTO
    {
        public int DemandDetailID { get; set; }
        public string IDTransaksi { get; set; }
        public string NoSanksi { get; set; }
        public string JenisPungutan { get; set; }
        public decimal? Nilai { get; set; }
    }

    public class UnVerifiedPaymentDTO
    {
        public int No { get; set; }
        public int _DebtorID { get; set; }
        public string NamaPerusahaan { get; set; }
        public int _SectorID { get; set; }
        public string NamaSector { get; set; }
        public string NoInvoice { get; set; }
        public decimal JumlahTagihan { get; set; }
        public string IDTransaksi { get; set; }
        public decimal JumlahPembayaran { get; set; }
        public DateTime  TanggalJatuhTempo { get; set; }
    }

    public class JSONHelper
    {
        public bool IsSuccess
        {
            get;
            set;
        }

        public string Message
        {
            get;
            set;
        }

        public object Data
        {
            get;
            set;
        }

    }

    public class Helper
    {
        public class Constanta
        {
            public const string MENU_ID = "menu_id";

            public const string USER_ID = "user_id";

        }

        public class String
        {
            public static string PropCase(string strText)
            {
                return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
            }
            public static string PropCaseStartLower(string strText)
            {
                string retVal = PropCase(strText);
                retVal = retVal.Substring(0, 1).ToLower() + retVal.Substring(1, (retVal.Length - 1));
                return retVal;
            }

            public static string Left(string param, int length)
            {
                string result = param.Substring(0, length);
                return result;

            }

            public static string Right(string param, int length)
            {
                string result = param.Substring(param.Length - length, length);
                return result;

            }

            public static string Mid(string param, int startindex, int length)
            {
                string result = param.Substring(startindex, length);
                return result;
            }

            public static string Mid(string param, int startindex)
            {
                string result = param.Substring(startindex);
                return result;
            }

            private static string RepeatedCharacters(char myCharacter, int repetitions)
            {
                string result = "";
                return result.PadLeft(repetitions, myCharacter);
            }

            public static string Digits(string str, int len)
            {
                string result = str;
                if (len > str.Length)
                {
                    result = RepeatedCharacters('0', len - str.Length) + str;
                }
                return result;
            }

            public string Terbilang(long nilai)
            {
                string[] bilangan = { "", "satu", "dua", "tiga", "empat", 
                            "lima", "enam", "tujuh", "delapan",
                            "sembilan", "sepuluh", "sebelas" };
                if (nilai < 12)
                    return " " + bilangan[nilai];
                else if (nilai < 20)
                    return Terbilang(nilai - 10) + " belas";
                else if (nilai < 100)
                    return Terbilang((int)(nilai / 10)) + " puluh" + Terbilang(nilai % 10);
                else if (nilai < 200)
                    return " seratus" + Terbilang(nilai - 100);
                else if (nilai < 1000)
                    return Terbilang((int)(nilai / 100)) + " ratus" + Terbilang(nilai % 100);
                else if (nilai < 2000)
                    return " seribu" + Terbilang(nilai - 1000);
                else if (nilai < 1000000)
                    return Terbilang((int)(nilai / 1000)) + " ribu" + Terbilang(nilai % 1000);
                else if (nilai < 1000000000)
                    return Terbilang((int)(nilai / 1000000)) + " juta" + Terbilang(nilai % 1000000);
                else if (nilai < 1000000000000)
                    return Terbilang((int)(nilai / 1000000000)) + " miliar" + Terbilang(nilai % 1000000000);
                else if (nilai < 1000000000000000)
                    return Terbilang((int)(nilai / 1000000000000)) + " triliun" + Terbilang(nilai % 1000000000000);
                else
                    return "";
            }
        }

        public enum Culture
        {
            English,
            Indonesian
        }

        public static string GetAppVirtualPath(System.Web.UI.Page page)
        {
            int port = page.Request.Url.Port;
            string baseServer = page.Request.Url.Host + ":" + port.ToString();
            string url = "http://" + baseServer + System.Web.HttpRuntime.AppDomainAppVirtualPath;

            return url;

        }

        public static string CreatePasswordHash(string pwd)
        {
            string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "sha1");

            return hashedPwd;
        }

        public static DateTime FormatDate(string value, Culture culture)
        {
            DateTime dt;
            if (culture == Culture.Indonesian)
                dt = Convert.ToDateTime(value, CultureInfo.GetCultureInfo("id-ID").DateTimeFormat);
            else
                dt = Convert.ToDateTime(value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat);

            return dt;

        }

        public static string ToMonthDayYear(string value)
        {
            string day = String.Left(value, 2);
            string month = String.Mid(value, 3, 2);
            string year = String.Right(value, 4);

            return month + "/" + day + "/" + year;

        }

        public static string ToSQLServerDateISO(string value)
        {
            string day = String.Left(value, 2);
            string month = String.Mid(value, 3, 2);
            string year = String.Right(value, 4);

            return year + month +day;

        }

        public static bool IsNumber(string val, System.Globalization.NumberStyles numberStyle, Culture culture)
        {
            Double result;
            if (culture == Culture.Indonesian)
                return Double.TryParse(val, numberStyle, CultureInfo.GetCultureInfo("id-ID").NumberFormat, out result);
            else
                return Double.TryParse(val, numberStyle, CultureInfo.GetCultureInfo("en-US").NumberFormat, out result);

        }

        public static decimal ToDecimal(string val, System.Globalization.NumberStyles numberStyle, Culture culture)
        {
            if (culture == Culture.Indonesian)
                return Decimal.Parse(val, numberStyle, CultureInfo.GetCultureInfo("id-ID").NumberFormat);
            else
                return Decimal.Parse(val, numberStyle, CultureInfo.GetCultureInfo("en-US").NumberFormat);

        }

        public static string JqGridFilterToSQLParams(HttpContext context)
        {
            string query = string.Empty;
            
            string searchField = ((context.Request["searchField"]) == null ? string.Empty : context.Request["searchField"].ToString());
            string searchString = ((context.Request["searchString"]) == null ? string.Empty : context.Request["searchString"].ToString());
            string searchOper = ((context.Request["searchOper"]) == null ? string.Empty : context.Request["searchOper"].ToString());

            string filters = ((context.Request["filters"]) == null ? string.Empty : context.Request["filters"].ToString());

            var jsonString = context.Server.UrlDecode(filters);

            jqGrid grid = Newtonsoft.Json.JsonConvert.DeserializeObject<jqGrid>(jsonString);

            System.Text.StringBuilder sbWhere = new System.Text.StringBuilder();

            if (grid != null)
            {
                foreach (jqGrid.Rule rule in grid.rules)
                {
                    var field = rule.field;
                    var value = rule.data;
                    var op = ConvertToSQLOperand(rule.op);

                    field = op.ToLower().Contains("like") ? "LOWER(" + field + ")" : field;
                    field = field.ToLower().Contains("date") ? "CONVERT(char(8), " + field + ", 112)" : field;

                    var filter = op.ToLower().Contains("like") ? "'%" + value.ToLower() + "%'" :
                        field.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(value) + "'" : "'" + value + "'"; // TextBox Filter

                    if (grid.groupOp.ToLower().Trim().Equals("or"))
                        sbWhere.AppendFormat("{0} {1} {2} {3}", field, op, filter, " OR ");
                    else
                        sbWhere.AppendFormat("{0} {1} {2} {3}", field, op, filter, " AND ");
                }

                if (sbWhere.Length > 1)
                {
                    sbWhere.Insert(0, " WHERE ");
                    query = sbWhere.ToString().Remove(sbWhere.Length - 4);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(searchField)) {

                    var op = ConvertToSQLOperand(searchOper);

                    searchField = op.ToLower().Contains("like") ? "LOWER(" + searchField + ")" : searchField;
                    searchField = searchField.ToLower().Contains("date") ? "CONVERT(char(8), " + searchField + ", 112)" : searchField;

                    var filter = op.ToLower().Contains("like") ? "'%" + searchString.ToLower() + "%'" :
                        searchField.ToLower().Contains("date") ? "'" + Helper.ToSQLServerDateISO(searchString) + "'" : "'" + searchString + "'"; // TextBox Filter
                    
                    sbWhere.AppendFormat(" WHERE {0} {1} {2}", searchField,  op, filter);

                   // sbWhere.AppendFormat("{2}", searchField, op, filter);
                    query = sbWhere.ToString();
                }

            }

            return query;
        }

        public static string ConvertToSQLOperand(string jqGridOperand)
        {
            string op = string.Empty;

            switch (jqGridOperand)
            {
                case ("eq"):
                    op = "=";
                    break;
                case ("cn"):
                    op = "like";
                    break;
                case ("lt"):
                    op = "<";
                    break;
                case ("le"):
                    op = "<=";
                    break;
                case ("gt"):
                    op = ">";
                    break;
                case ("ge"):
                    op = ">=";
                    break;
                default:
                    op = "";
                    break;
            }


            return op;
        }

        public static string HashCaptcha(string value)
        {
            int hash = 5381;
            value = value.ToUpper();
            for (int i = 0; i < value.Length; i++)
            {
                hash = ((hash << 5) + hash) + value[i];
            }
            return hash.ToString();
        }

        public static void SendEmail(string smtpServer, int smtpPort, string sender, string senderAlias, string senderPassword, string receiver, string subject, string body, System.IO.MemoryStream mstream, string fileName)
        {
            MailMessage message = new MailMessage();
            LinkedResource logo = new LinkedResource(HttpContext.Current.Server.MapPath(@"~/images/logo.png")); 
            logo.ContentId = "imgLogo";

            string signature = @"<br/><br/><img src='cid:imgLogo' alt='logo OJK' /><br/>OTORITAS JASA KEUANGAN<br/>
Gedung Soemitro Djojohadikusumo,<br/>Jalan Lapangan Banteng Timur No. 2-4, Jakarta 10710<br/>Telp. 021 – 3858001<br/>Faks. 021 – 3857919";

            var contentEmail = "<html><body>" + body + signature + "</body></html>";

            var view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(contentEmail, null, "text/html");
            view.LinkedResources.Add(logo);

            message.From = new MailAddress(sender, senderAlias);
            message.To.Add(new MailAddress(receiver));

            message.Subject = subject;
            message.Body = contentEmail;
            message.IsBodyHtml = true;

            Attachment data = new Attachment(mstream, fileName, MediaTypeNames.Application.Pdf);
            message.Attachments.Add(data);

            message.AlternateViews.Add(view);

            System.Net.NetworkCredential credential = new System.Net.NetworkCredential();
            credential.UserName = sender;
            credential.Password = senderPassword;

            SmtpClient smtp = new SmtpClient(smtpServer, smtpPort);
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = false;
            smtp.Credentials = credential;

            try
            {
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally 
            {
                logo.Dispose();
                data.Dispose();            
            }

        }

        public static void SendEmail(string  smtpServer, int smtpPort, string sender, string senderAlias, string senderPassword, string receiver, string subject, string body,string ccEmail)
        {
            MailMessage message = new MailMessage();

            message.From = new MailAddress(sender, senderAlias);
            //message.To.Add(new MailAddress(receiver));

            string[] ids = receiver.Split(',');
            foreach (string id in ids)
            {
                message.To.Add(new MailAddress(id));
            }


            message.CC.Add(new MailAddress(ccEmail));
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;

            System.Net.NetworkCredential credential = new System.Net.NetworkCredential();
            credential.UserName = sender;
            credential.Password = senderPassword;

            SmtpClient smtp = new SmtpClient(smtpServer, smtpPort);
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = true;
            smtp.Credentials = credential;

            try
            {
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {

            }

        }
    }

    public class jqGrid
    {

        public string groupOp { get; set; }
        public Rule[] rules { get; set; }

        public class Rule
        {
            public string field { get; set; }
            public string op { get; set; }
            public string data { get; set; }
        }
    
    }

}
